package com.tianshi.yingxue.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.tianshi.yingxue.dao.UserMapper;
import com.tianshi.yingxue.entity.User;
import com.tianshi.yingxue.service.UserService;
import com.tianshi.yingxue.utils.AliyunOssUtils;
import com.tianshi.yingxue.utils.FileUploadConstance;
import com.tianshi.yingxue.vo.UserExportVO;
import com.tianshi.yingxue.vo.UserVO;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Transactional

public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserVO queryPage(int page, int pageSize) {
        int offset = (page - 1) * pageSize;
        RowBounds rowBounds = new RowBounds(offset, pageSize);
        List<User> users = userMapper.selectByRowBounds(new User(), rowBounds);
        int total = userMapper.selectCount(null);
        UserVO userVO = new UserVO();
        userVO.setTotal(total);
        userVO.setRows(users);
        userVO.setPage(page);
        return userVO;
    }

    @Override
    public String uploadHeadImg(MultipartFile headImg, String oldImg) throws IOException {
        String fileName = headImg.getOriginalFilename();
        fileName = UUID.randomUUID() + "-" +fileName;
        String objName = FileUploadConstance.USER_HEADIMG_DIR + fileName;
        if (oldImg!=null){
            AliyunOssUtils.deleteFile(FileUploadConstance.BUCKET, oldImg);
        }
        AliyunOssUtils.uploadFileBytes(headImg,FileUploadConstance.BUCKET, objName);
        return FileUploadConstance.BUCKET_DOMAIN_NAME+objName;
    }



    @Override
    public void addUser(User user) {
        userMapper.insertSelective(user);
    }
    @Override
    public User queryById(int id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public void deleteUser(int id) {
        userMapper.deleteByPrimaryKey(id);
    }
    @Override
    public void exportUserExcel(HttpServletResponse response) throws IOException {
        try {
            // 1. 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("员工信息", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 2. 查询所有用户数据（不分页）
            List<User> userList = userMapper.selectAll();

            // 3. 转换为导出VO
            List<UserExportVO> exportList = userList.stream()
                    .map(this::convertToExportVO)
                    .collect(Collectors.toList());

            // 4. 使用EasyExcel导出
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), UserExportVO.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("员工信息").build();
            excelWriter.write(exportList, writeSheet);
            excelWriter.finish();

        } catch (Exception e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }

    /**
     * 将User实体转换为导出VO
     */
    private UserExportVO convertToExportVO(User user) {
        UserExportVO exportVO = new UserExportVO();
        exportVO.setId(user.getId());
        exportVO.setUsername(user.getUsername());
        exportVO.setHeadImg(user.getHeadImg()); // OSS URL
        exportVO.setPhone(user.getPhone());
        exportVO.setSign(user.getSign());
        exportVO.setWechat(user.getWechat());
        exportVO.setStatus("1".equals(user.getStatus()) ? "正常" : "冻结");
        exportVO.setCreateTime(user.getCreateTime());
        exportVO.setSex(user.getSex());
        exportVO.setCity(user.getCity());
        return exportVO;
    }
}
